package com.um.springboot.starter.scheduled;

import cn.hutool.core.util.StrUtil;
import com.um.springboot.starter.annotation.ConditionalOnSpecificInstance;
import com.um.springboot.starter.dao.CommonDao;
import com.um.springboot.starter.properties.HshProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author renjunwei
 * @since 2022/12/5
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
@ConditionalOnSpecificInstance
public class LogTask {

    @Autowired
    private CommonDao dao;

    @Autowired
    private HshProperties hshProperties;

    @Async
    @Scheduled(cron = "${hsh.clear-log.cron:0 0 2/4 * * ?}")
    public void autoDelete() {
        if (!hshProperties.getClearLog().isEnabled()) {
            return;
        }

        List<HshProperties.ClearLogProperties.LogTableProperties> tables = hshProperties.getClearLog().getTables();
        for (HshProperties.ClearLogProperties.LogTableProperties table : tables) {
            String sql = StrUtil.format("DELETE FROM {} WHERE {} < DATE_SUB(NOW(), INTERVAL {} DAY)",
                    table.getName(), table.getDatetimeField(), table.getDays());
            int limit = hshProperties.getClearLog().getLimit();
            if (limit > 0) {
                sql += StrUtil.format(" ORDER BY {} ASC LIMIT {}", table.getDatetimeField(), limit);
            }
            try {
                log.info("执行定期清理表：{}", sql);
                int totalCount = 0;
                if (limit > 0) {
                    int count;
                    do {
                        count = dao.executeSQLCount(sql, new Object[]{});
                        totalCount += count;
                    } while (count == limit);
                } else {
                    totalCount = dao.executeSQLCount(sql, new Object[]{});
                }
                log.info("完成定期清理表：{}, 数量：{}", table.getName(), totalCount);
            } catch (Exception e) {
                log.error(StrUtil.format("定期清理表出错：{}", table.getName()), e);
            }
        }
    }

    @Async
    @Scheduled(cron = "${hsh.clear-log.optimize-cron:0 0 3 ? * 1}")
    public void autoOptimize() {
        if (!hshProperties.getClearLog().isOptimizeEnabled()) {
            return;
        }

        List<HshProperties.ClearLogProperties.LogTableProperties> tables = hshProperties.getClearLog().getTables();
        tables.forEach(table -> {
            String sql = StrUtil.format("OPTIMIZE TABLE {}", table.getName());
            log.info("执行定期优化表：{}", sql);
            dao.queryListBySQL(sql, new Object[]{});
            log.info("完成定期优化表：{}", table.getName());
        });
    }
}
